package com.ericsson.enap.modules.ebmLog.utils;

import com.ericsson.common.util.DateUtils;
import com.ericsson.common.util.LogFileName;
import com.ericsson.common.util.LoggerUtils;
import com.ericsson.enap.modules.sys.entity.EnipNetelement;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;

import java.math.BigInteger;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;


/**
 * @description: 5gc ebm多维工具类
 * @author: wangjingshi
 * @create: 2021-11-10 10:40
 */
public class VgcEbmLogUtil {

    public static final Logger log = LoggerUtils.Logger(LogFileName.VgcEbmLogJob);

    public static void executeCmd(String cmd) {
        //log.info(" cmd: "+cmd);
        Process process = null;
        String command[] = new String[3];
        command[0] = "sh";
        command[1] = "-c";
        command[2] = cmd;
        try {
            process = Runtime.getRuntime().exec(command);
            try {
                process.waitFor();
            } catch (InterruptedException e) {
                e.printStackTrace();
                log.error(" ===== InterruptedException in VgcEbmLogUtil.executeCmd =====" + e.getMessage() + " cmd:" + cmd,e);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(" ===== Exception in VgcEbmLogUtil.executeCmd =====" + e.getMessage() + " cmd:" + cmd,e);
        } finally {
            process.destroy();
        }
    }
    /**
     * 获取nci系列表的创建语句
     * @param tableNameTime
     * @param net
     * @param eventType
     * @return
     */
    public static StringBuffer getNciSql(String tableNameTime, EnipNetelement net, String eventType) {
        StringBuffer sb_n_tac;
        sb_n_tac = new StringBuffer("CREATE TABLE IF NOT EXISTS `"+ tableNameTime +"_"+ net.getId()+"_"+ eventType +"_nci` (");
        sb_n_tac.append("`DATETIME` varchar(20) DEFAULT NULL,")
                .append("`NCI` varchar(20) DEFAULT NULL,")
                .append("`GNBID` varchar(20) DEFAULT NULL,")
                .append("`FAILURE_COUNT` int(20) DEFAULT NULL,")
                .append("`TOTAL_COUNT` int(20) DEFAULT NULL,")
                .append("`SUCCESS_RATE` double(20,6) DEFAULT NULL,")
                .append("KEY `"+ eventType +"_nci_index` (`DATETIME`");
        sb_n_tac.append(") USING BTREE")
                .append(") ENGINE=InnoDB DEFAULT CHARSET=utf8;");
        return sb_n_tac;
    }

    /**
     * 获取n_tac系列表的创建语句
     * @param tableNameTime
     * @param net
     * @param eventType
     * @return
     */
    public static StringBuffer getNTacSql(String tableNameTime, EnipNetelement net, String eventType) {
        StringBuffer sb_n_tac;
        sb_n_tac = new StringBuffer("CREATE TABLE IF NOT EXISTS `"+ tableNameTime +"_"+ net.getId()+"_"+ eventType +"_n_tac` (");
        sb_n_tac.append("`DATETIME` varchar(20) DEFAULT NULL,")
                .append("`N_TAC` varchar(20) DEFAULT NULL,")
                .append("`FAILURE_COUNT` int(20) DEFAULT NULL,")
                .append("`TOTAL_COUNT` int(20) DEFAULT NULL,")
                .append("`SUCCESS_RATE` double(20,6) DEFAULT NULL,")
                .append("KEY `"+ eventType +"_n_tac_index` (`DATETIME`");
        sb_n_tac.append(") USING BTREE")
                .append(") ENGINE=InnoDB DEFAULT CHARSET=utf8;");
        return sb_n_tac;
    }

    /**
     * 获取chart系列表的创建语句
     * @param tableNameTime
     * @param net
     * @param eventType
     * @return
     */
    public static StringBuffer getChartSql(String tableNameTime, EnipNetelement net, String eventType, String[] conditionArrs) {
        StringBuffer sb_chart;
        sb_chart = new StringBuffer("CREATE TABLE IF NOT EXISTS `"+ tableNameTime +"_"+ net.getId()+"_"+ eventType +"_chart` (");
        sb_chart.append("`TIME` varchar(8) DEFAULT NULL,");
        for(String condition: conditionArrs){
            sb_chart.append("`"+condition+"` varchar(50) DEFAULT NULL,");
        }
        sb_chart.append("`TOTAL` int(10) DEFAULT NULL,")
                .append("`ABORT` int(10) DEFAULT NULL,")
                .append("`REJECT` int(10) DEFAULT NULL,")
                .append("`IGNORE` int(10) DEFAULT NULL,")
                .append("`DATETIME` varchar(10) DEFAULT NULL,")
                .append("KEY `"+ eventType +"_index` (`TIME`");
        for(String condition: conditionArrs){
            sb_chart.append(",`"+condition+"`");
        }
        sb_chart.append(") USING BTREE")
                .append(") ENGINE=InnoDB DEFAULT CHARSET=utf8;");
        return sb_chart;
    }

    /**
     * 获取ccScc系列表的创建语句
     * @param tableNameTime
     * @param net
     * @param eventType
     * @param conditionArrs
     * @return
     */
    public static StringBuffer getCcSccSql(String tableNameTime, EnipNetelement net, String eventType, String[] conditionArrs) {
        StringBuffer sb_ccScc;
        sb_ccScc = new StringBuffer("CREATE TABLE IF NOT EXISTS `"+ tableNameTime +"_"+ net.getId()+"_"+ eventType +"` (");
        sb_ccScc.append("`TIME` varchar(8) DEFAULT NULL,")
                .append("`CAUSE_CODE` smallint(5) DEFAULT NULL,")
                .append("`SUB_CAUSE_CODE` smallint(5) DEFAULT NULL,")
                .append("`CAUSE_PROT_TYPE` varchar(10) DEFAULT NULL,");
        for(String condition: conditionArrs){
            sb_ccScc.append("`"+condition+"` varchar(50) DEFAULT NULL,");
        }
        sb_ccScc.append("`EVENT_RESULT` smallint(1) DEFAULT NULL,")
                .append("`K_VALUE` int(10) DEFAULT NULL,")
                .append("`SEVEN_AVE` double(20,2) DEFAULT NULL,")
                .append("KEY `"+ eventType +"_index` (`TIME`,`CAUSE_CODE`,`SUB_CAUSE_CODE`,`EVENT_RESULT`");
        for(String condition: conditionArrs){
            sb_ccScc.append(",`"+condition+"`");
        }
        sb_ccScc.append(") USING BTREE")
                .append(") ENGINE=InnoDB DEFAULT CHARSET=utf8;");
        return sb_ccScc;
    }

    /**
     * 获取Dimension系列表的创建语句
     * @param tableNameTime
     * @param net
     * @param eventType
     * @param conditionArrs
     * @return
     */
    public static StringBuffer getDimensionSql(String tableNameTime, EnipNetelement net, String eventType, String[] conditionArrs, String[] dimensionArr) {
        StringBuffer sb_dimension;
        sb_dimension = new StringBuffer("CREATE TABLE IF NOT EXISTS `"+ tableNameTime +"_"+ net.getId()+"_"+ eventType +"_dimension` (");
        sb_dimension.append("`TIME` varchar(8) DEFAULT NULL,")
                .append("`CAUSE_CODE` smallint(5) DEFAULT NULL,")
                .append("`SUB_CAUSE_CODE` smallint(5) DEFAULT NULL,");
        for(String condition: conditionArrs){
            sb_dimension.append("`"+condition+"` varchar(50) DEFAULT NULL,");
        }
        sb_dimension.append("`K_NAME` varchar(50) DEFAULT NULL,")
                .append("`K_KEY` varchar(50) DEFAULT NULL,")
                .append("`EVENT_RESULT` smallint(1) DEFAULT NULL,")
                .append("`K_VALUE` int(10) DEFAULT NULL,")
                .append("KEY `"+ eventType +"_index` (`TIME`,`CAUSE_CODE`,`SUB_CAUSE_CODE`,`K_NAME`");
        for(String condition: conditionArrs){
            sb_dimension.append(",`"+condition+"`");
        }
        sb_dimension.append(") USING BTREE")
                .append(") ENGINE=InnoDB DEFAULT CHARSET=utf8")
                .append("/*!50500 PARTITION BY LIST COLUMNS(K_NAME)")
                .append("(");
                for(int i=0;i<dimensionArr.length;i++){
                    if(i == (dimensionArr.length-1)){
                        sb_dimension.append("PARTITION "+dimensionArr[i]+" VALUES IN ('"+dimensionArr[i]+"') ENGINE = InnoDB) */;");
                    }else{
                        sb_dimension.append("PARTITION "+dimensionArr[i]+" VALUES IN ('"+dimensionArr[i]+"') ENGINE = InnoDB,");
                    }
                }
        return sb_dimension;
    }

    public static StringBuffer getPagingSubSql(String tableNameTime, EnipNetelement net){
        StringBuffer sb_paging_sub;
        sb_paging_sub = new StringBuffer("CREATE TABLE IF NOT EXISTS `"+ tableNameTime +"_"+ net.getId()+"_amf_paging_sub` (");
        sb_paging_sub.append("`TIME` varchar(8) DEFAULT NULL,")
                .append("`K_NAME` varchar(50) DEFAULT NULL,")
                .append("`K_KEY` varchar(50) DEFAULT NULL,")
                .append("`EVENT_RESULT` smallint(1) DEFAULT NULL,")
                .append("`K_VALUE` int(10) DEFAULT NULL,")
                .append("KEY `amf_paging_sub_index` (`TIME`,`K_NAME`");
        sb_paging_sub.append(") USING BTREE")
                .append(") ENGINE=InnoDB DEFAULT CHARSET=utf8")
                .append("/*!50500 PARTITION BY LIST COLUMNS(K_NAME)")
                .append("(PARTITION duration VALUES IN ('duration') ENGINE = InnoDB,")
                .append("PARTITION paging_attempts VALUES IN ('paging_attempts') ENGINE = InnoDB,")
                .append("PARTITION total_no_of_paged_ngran_node VALUES IN ('total_no_of_paged_ngran_node') ENGINE = InnoDB) */;");
        return sb_paging_sub;
    }



    //根据当前ebm二进制文件获取当前日期
    public static Date getDate(Integer delay) {
        String dateTime = DateUtils.getEbmLogStartMinDateTime(15+ delay);
        log.info("=======delay:"+ delay +" =======dateTime:"+dateTime);
        Date date = null;
        try {
            date = new SimpleDateFormat("yyyy-MM-dd").parse(dateTime);
        } catch (ParseException e) {
            log.error(e.getMessage(), e);
        }
        return date;
    }

    //Paging_attempts转换
    public static String getPaging_attempts(String str){
        Integer d = Integer.parseInt(str);
        if(d==1){
            return "1次";
        }else if(d==2){
            return "2次";
        }else if(d==3){
            return "3次";
        }else if(d==4){
            return "4次";
        }else{
            return "4次以上";
        }
    }

    public static Map<String,Integer> paging_attemptsMap(){
        Map<String,Integer> map = new HashMap<>();
        map.put("1次",0);
        map.put("2次",0);
        map.put("3次",0);
        map.put("4次",0);
        map.put("4次以上",0);
        return map;
    }

    //Total_no_of_paged_ngran_node转换
    public static String getTotal_no_of_paged_ngran_node(String str){
        Integer d = Integer.parseInt(str);
        if(d==1){
            return "1次";
        }else if(d>1&&d<=100){
            return "2-100次";
        }else if(d>100&&d<=300){
            return "100-300次";
        }else if(d>300&&d<=500){
            return "300-500次";
        }else{
            return "500次以上";
        }
    }

    public static Map<String,Integer> total_no_of_paged_ngran_nodeMap(){
        Map<String,Integer> map = new HashMap<>();
        map.put("1次",0);
        map.put("2-100次",0);
        map.put("100-300次",0);
        map.put("300-500次",0);
        map.put("500次以上",0);
        return map;
    }

    //duration转换
    public static String getDuration(String str){
        Integer d = Integer.parseInt(str);
        if(d>=0&&d<=500){
            return "0-500ms";
        }else if(d>500&&d<=1000){
            return "500ms-1s";
        }else if(d>1000&&d<=2000){
            return "1s-2s";
        }else if(d>2000&&d<=3000){
            return "2s-3s";
        }else{
            return "3s以上";
        }
    }

    public static Map<String,Integer> DurationMap(){
        Map<String,Integer> map = new HashMap<>();
        map.put("0-500ms",0);
        map.put("500ms-1s",0);
        map.put("1s-2s",0);
        map.put("2s-3s",0);
        map.put("3s以上",0);
        return map;
    }

    //获取nci
    public static String getGnbid(String str){
        if(isInteger(str)){
            String nci_2 = new BigInteger(str).toString(2);
            String gnbid_2 = nci_2.substring(0,24-(36-nci_2.length()));
            String gnbid_10 = new BigInteger(gnbid_2,2).toString();
            return gnbid_10;
        }else{
            return str;
        }
    }

    //获取amfi
    public static String getAmfi(String region_id,String set_id,String pointer){
        if(StringUtils.isNotEmpty(region_id) && StringUtils.isNotEmpty(set_id) && StringUtils.isNotEmpty(pointer)){
            return region_id+"-"+set_id+"-"+pointer;
        }else{
            return "undefined";
        }
    }

    //获取imsi
    public static String getImsi(String imsi){
        if(isInteger(imsi)){
            String str = Long.toString(Long.parseLong(imsi), 36);
            if(str.length()==10){
                return "imsi-"+str.substring(5)+str.substring(0,5);
            }else{
                return "imsi-"+str;
            }
        }else{
            return imsi;
        }
    }

    //获取msisdn
    public static String getMsisdn(String msisdn){
        if(isInteger(msisdn)){
            String str = "0"+Long.toString(Long.parseLong(msisdn),36);
            if(str.length()==10){
                return "msisdn-"+str.substring(5)+str.substring(0,5);
            }else{
                return "msisdn-"+str;
            }
        }else{
            return msisdn;
        }
    }

    //判断是否是数字
    public static boolean isInteger(String str) {
        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
        return pattern.matcher(str).matches();
    }

    //获取具体的时间点（HH:mm:00）
    public static String getTimePoint(String hour,String minute){
        if(hour.length()==1){
            hour = "0"+hour;
        }
        if(minute.length()==1){
            minute = "0"+minute;
        }
        return hour+":"+minute+":00";
    }

    //获取具体的15分钟时间点（HH:00/15/30/45:00）
    public static String getTimePoint15(String hour,String minute){
        int min = Integer.parseInt(minute);
        if(Integer.parseInt(hour)<10){
            hour = "0"+hour;
        }
        if(min>=0&&min<15){
            return hour+":00:00";
        }else if(min>=15&&min<30){
            return hour+":15:00";
        }else if(min>=30&&min<45){
            return hour+":30:00";
        }else{
            return hour+":45:00";
        }
    }

    //获取具体的时间点
    public static Long getDateTimePoint(String dateTime,String hour,String minute,String second,String millisecond){
        String date = dateTime.substring(0,10);
        if(hour.length()==1){
            hour = "0"+hour;
        }
        if(minute.length()==1){
            minute = "0"+minute;
        }
        if(second.length()==1){
            second = "0"+second;
        }
        if(millisecond.length() == 1){
            millisecond = "00"+millisecond;
        }else if(millisecond.length() == 2){
            millisecond = "0"+millisecond;
        }
        String dateTimePoint = date+" "+hour+":"+minute+":"+second+"."+millisecond;
        return dateToStamp(dateTimePoint);
    }

    public static long dateToStamp(String str){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        Date date = null;
        try {
            date = sdf.parse(str);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        long ts = date.getTime();
        return ts;
    }

    public static String stampToDate(long milliSecond){
        Date date = new Date();
        date.setTime(milliSecond);
        return new SimpleDateFormat("HH:mm:ss.SSS").format(date);
    }


}
